package com.mty.mydemo;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.net.Uri;
import android.os.Environment;
import android.widget.ProgressBar;
import com.igexin.sdk.PushManager;
import com.litesuits.android.log.Log;
import com.litesuits.common.utils.AndroidUtil;
import com.litesuits.common.utils.PackageUtil;
import com.litesuits.common.utils.TelephoneUtil;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.request.AbstractRequest;
import com.litesuits.http.request.FileRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.litesuits.sdk.act.LiteActivity;
import com.litesuits.sdk.listener.AbsActivityHttpListener;
import com.litesuits.sdk.views.CustomDialog;
import com.mty.mydemo.receiver.MsgHanlder;
import com.qunduikj.sjb.sdk.AppSdk;
import com.qunduikj.sjb.sdk.consts.AppConst;
import com.qunduikj.sjb.sdk.model.enums.MobEvent;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.util.Arrays;

/**
 * @author MaTianyu on 2015-05-05
 */
public class App extends com.litesuits.sdk.LiteApp {
    private static final String TAG = App.class.getSimpleName();
    protected static App instance;
    //private static String MY_APP_KEY = "351a9dd8477320b6311a5097";//测试key


    public static synchronized App getInstance() {
        return instance;
    }

    protected MsgHanlder msgHanlder;
    protected String processName;
    protected Activity homeActivity;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        ActivityManager.RunningAppProcessInfo processInfo = getCurrentProcess(this);
        PackageInfo info = PackageUtil.getAppPackageInfo(this);
        processName = processInfo.processName;
        if (processName == null) {
            processName = info.packageName;
        }
        if (!processName.contains("pushservice")) {
            AndroidUtil.printSystemInfo();
//            TelephoneUtil.printTelephoneInfo(this);
            Log.i(TAG, "init SDK ----------------------->: " + processInfo.processName);

            AppSdk.initialize(instance);
            msgHanlder = new MsgHanlder();
        } else {
            Log.e(TAG, "no need to init SDK ----------------------->: " + processInfo.processName);
        }

        Log.i(TAG, "process pid: " + android.os.Process.myPid()
                   + "  uid: " + android.os.Process.myUid()
                   + "  tid: " + android.os.Process.myTid());
        Log.i(TAG, "process processName: " + processInfo.processName);
        Log.i(TAG, "process pkgList: " + Arrays.toString(processInfo.pkgList));


    }

    public AppSdk getSdk() {
        return AppSdk.getInstance();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }


    public void onHomeActCreate(LiteActivity homeActivity) {
        this.homeActivity = homeActivity;
        Log.i(TAG, "注册： 电话 个推  --------------------> ");
        PushManager.getInstance().initialize(this.getApplicationContext());// 个推初始化
        updatePushCID();// 上传推送CID
        checkNewVersion(homeActivity);// 检测最新版本
    }

    public MsgHanlder getMsgHanlder() {
        return msgHanlder;
    }


    public void exitHomeActivity() {
        if (homeActivity != null) {
            homeActivity.finish();
        }
    }

    /**
     * 检查新版本
     */
    private void checkNewVersion(final LiteActivity activity) {
        PackageInfo packInfo = activity.getPackInfo();
        if (packInfo != null) {
            final String localVercode = packInfo.versionName;
            //调用接口检查版本更新然后更新版本
            //            doNewVerUp(must, activity, apkurl, version.id, netVersion, VersionContent);// 更新新版本
        }
    }

    /**
     * 更新新版本
     * must  是否必须  如果是则不会出现取消键
     * apkurl apk的下载地址
     * netVersion 新版本的版本等级
     * content 更新内容
     */
    private void doNewVerUp(boolean must, final Activity activity, final String apkurl, final int version_id,
                            final String netVersion, String content) {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        content = content.replaceAll("/n", "\\\n");
        builder.setMessage("是否更新货车侠新版本V" + netVersion + "？\n" + content);
        builder.setTitle(R.string.tips_label);
        builder.setPositiveButton(R.string.go_newver, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                MobclickAgent.onEvent(activity, MobEvent.ToUpdate.getEventID());//更新
                downApk(activity, apkurl);
            }
        });
        builder.setCancelable(false);
        if (!must) {
            builder.setNegativeButton(R.string.cancel, null);
        }
        Dialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }

    /**
     * 下载apk
     */
    public void downApk(final Activity activity, final String url) {
        final ProgressBar bar = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal);
        bar.setMax(100);
        bar.setProgress(0);
        final CustomDialog dialog = new CustomDialog.Builder(activity)
                .setTitle(R.string.uploading)
                .setContentView(bar)
                .create();
        dialog.show();
        String path = new File(Environment
                .getExternalStorageDirectory(), AppConst.UPDATE_SERVERAPK)
                .getAbsolutePath();
        FileRequest request = new FileRequest(url, path)
                .setMethod(HttpMethods.Get)
                .setHttpListener(new AbsActivityHttpListener<File>(activity, true, true, false) {
                    @Override
                    public void onLoading(AbstractRequest<File> request, long total, long len) {
                        if (bar != null && bar.isShown()) {
                            bar.setMax((int) total);
                            bar.setProgress((int) len);
                        }

                        //System.out.println("t: " + total + "  len: " + len);
                    }

                    @Override
                    public void onSuccess(File file, Response<File> response) {
                        dialog.dismiss();
                        runApk();
                    }

                    @Override
                    public void onFailure(HttpException e, Response<File> response) {
                        dialog.dismiss();
                        CustomDialog dialog = new CustomDialog.Builder(activity)
                                .setMessage(R.string.upload_fail)
                                .setPositiveButton(R.string.tips_sure, null)
                                .create();
                        dialog.show();
                    }
                });
        getSdk().getLiteHttp().executeAsync(request);
    }

    /**
     * 运行 apk
     */
    private void runApk() {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(
                    Uri.fromFile(new File(Environment.getExternalStorageDirectory(), AppConst.UPDATE_SERVERAPK)),
                    "application/vnd.android.package-archive");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //通过个推接口获取配置并上传
    private void updatePushCID() {
        // 从AndroidManifest.xml的meta-data中读取SDK配置信息
        String clientid = PushManager.getInstance().getClientid(this);
        Log.e(TAG,"个推SDK配置信息"+clientid);
        if (clientid != null) {
            //getSdk().executeAsync(new UpdateCIDParam(clientid));
        }

    }


    public ActivityManager.RunningAppProcessInfo getCurrentProcess(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager service = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : service.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return appProcess;
            }
        }
        return null;
    }


}
